package org.javascud.extensions.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.List;

/**
 * a Watcher for monitor zookeeper by getChildren
 *
 * @author Felix Zhang   Date:2010-10-16 14:39
 */
public abstract class ZooKeeperChildrenWatcher implements Watcher {
    private ZooKeeper zooKeeper;
    private String groupName;
    private GroupMemberCenter gmc = null;

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    @Override
    public void process(WatchedEvent event) {
        fetchAndUpdate();
    }

    private void fetchAndUpdate() {
        //get children and register watcher again
        List<String> members = gmc.fetchGroupMembers(groupName, this);

        updateData(members);
    }

    protected abstract void updateData(List<String> members);

    public void init() {
        if (zooKeeper != null) {
            gmc = new GroupMemberCenter();
            gmc.setZooKeeper(zooKeeper);

            fetchAndUpdate();
        }
    }
}
